package com.heima.article.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.article.dto.ArticleDto;
import com.heima.article.dto.ArticleHomeDto;
import com.heima.article.dto.ArticleInfoDto;
import com.heima.article.entity.ApArticle;
import com.heima.article.entity.ApArticleContent;
import com.heima.article.mapper.ApArticleMapper;
import com.heima.article.service.IApArticleContentService;
import com.heima.article.service.IApArticleService;
import com.heima.common.dto.PageResponseResult;
import com.heima.common.dto.ResponseResult;
import com.heima.common.enums.AppHttpCodeEnum;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * <p>
 * 文章信息表，存储已发布的文章 服务实现类
 * </p>
 *
 * @author itheima
 * @since 2022-07-31
 */
@Service
public class ApArticleServiceImpl extends ServiceImpl<ApArticleMapper, ApArticle> implements IApArticleService {

    @Autowired
    private IApArticleContentService articleContentService;
    @Autowired
    private StringRedisTemplate redisTemplate;
    /**
     * 提供给自媒体微服务进行远程调用
     * 将文章保存到发布文章表中  1.保存文章信息  2.包含文章内容
     *
     * @param dto 文章信息
     * @return 保存后文章ID
     */
    @Override
    public ResponseResult<Long> saveArticle(ArticleDto dto) {
        //1.将提交的DTO转为PO对象-得到文章基本信息ApArticle对象
        ApArticle article = new ApArticle();
        BeanUtils.copyProperties(dto, article);

        //2.判断操作是新增还是修改（根据主键）
        if (dto.getId() == null) {
            //2.1 完成新增文章
            this.save(article);
            //2.2 完成新增文章内容
            ApArticleContent articleContent = new ApArticleContent();
            articleContent.setArticleId(article.getId());
            articleContent.setContent(dto.getContent());
            articleContentService.save(articleContent);
        } else {
            //2.3 完成修改文章信息
            this.updateById(article);

            //2.4 修改文章内容 update ap_article_content s set s.content = ? where s.article_id = ?
            LambdaUpdateWrapper<ApArticleContent> updateWrapper = new LambdaUpdateWrapper<>();
            updateWrapper.set(ApArticleContent::getContent, dto.getContent());
            updateWrapper.eq(ApArticleContent::getArticleId, dto.getId());
            articleContentService.update(updateWrapper);
        }
        //3.保存后返回文章ID
        return ResponseResult.okResult(article.getId());
    }

    /**
     * 首次进入首页：加载文章列表
     * @param dto
     * @param i
     * @return
     */
    @Override
    public ResponseResult loadArticle(ArticleHomeDto dto, int i) {
        if (dto.getLoaddir().equals(1)){
//            查询推荐页数据
            String redisKey = "leadnews:article:hot:page:"+dto.getChannelId();
            long start = 0;
            long end = 30;
            Set<String> strings = redisTemplate.opsForZSet().reverseRange(redisKey, start, end);
            if (!CollectionUtils.isEmpty(strings)){
                List<ApArticle> articleList = strings.stream().map(articleStr -> {
                    ApArticle apArticle = JSON.parseObject(articleStr, ApArticle.class);
                    return apArticle;
                }).collect(Collectors.toList());
                Integer total = articleList.size();
                return new PageResponseResult(1L,dto.getSize(),total.longValue(),articleList);
            }
        }
//        构建分页对象
        IPage<ApArticle> page = new Page<>(1, dto.getSize());
//        构建查询条件
        LambdaQueryWrapper<ApArticle> wrapper = new LambdaQueryWrapper<>();
//        -设置频道条件
        if (ObjectUtils.isNotEmpty(dto.getChannelId())){
            wrapper.eq(ApArticle::getChannelId,dto.getChannelId());
        }
//        -设置时间条件 0:最新 1:更多
        if (i == 0){
            wrapper.gt(ApArticle::getPublishTime,dto.getMaxTime());
        }else {
            wrapper.lt(ApArticle::getPublishTime,dto.getMinTime());
        }

//        -未下架
        wrapper.eq(ApArticle::getIsDown,false);
//        -未删除
        wrapper.eq(ApArticle::getIsDelete,false);
//        查询
        this.page(page,wrapper);
        PageResponseResult<List<ApArticle>> result = new PageResponseResult<>(1L, dto.getSize(), page.getTotal(), page.getRecords());
        return result;
    }

    /**
     * 查询文章详情
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult loadArticleInfo(ArticleInfoDto dto) {
        //1.根据文章ID查询文章信息
        ApArticle article = this.getById(dto.getArticleId());
        if (article.getIsDown() || article.getIsDelete()) {
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        //2.根据文章ID查询文章内容信息
        LambdaQueryWrapper<ApArticleContent> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(ApArticleContent::getArticleId, dto.getArticleId());
        ApArticleContent content = articleContentService.getOne(queryWrapper);

        //3.封装响应数据
        HashMap<String, Object> result = new HashMap<>();
        result.put("config", article);
        result.put("content", content);
        return ResponseResult.okResult(result);
    }
}
